package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {

        // 1 参数检查
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不存在");
        }
        // 2 条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        // 3 返回结果
        IPage<ApUserRealname> realnameIPage = page(page, wrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),realnameIPage.getTotal(),realnameIPage.getRecords());
    }

    @Autowired
    private ApUserMapper apUserMapper;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.参数校验
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"需要传入参数");
        }
        //根据id去ap_user_realname查询实名认证信息
        ApUserRealname apUserRealname = this.getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId,dto.getId()));
        if (apUserRealname==null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"实名信息不存在");
        }
        //3.检查实名认证状态  必须为1
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"实名认证状态不为待审核");
        }
        //4.根据实名认证关联的userId查询 apuser关联是否存在
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, apUserRealname.getUserId()));
        if(apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息 关联 app的用户不存在");
        }
        //5.修改实名认证状态
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //6.判断审核状态
        //6.1如果审核状态为2  直接return
        if(AdminConstants.FAIL_AUTH.equals(status)){
            return ResponseResult.okResult();
        }
        //6.2 如果审核状态为9 继续
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //7. 开通自媒体账户
            WmUser wmUser = createWmUser(apUser);

            //8. 创建作者信息
            createApAuthor(wmUser);

        }
        return ResponseResult.okResult();
    }

    @Autowired
    private WemediaFeign wemediaFeign;
    
    /**开通自媒体账户
     *
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {

        //远程调用WemediaFeign接口 查询用户是否已经开通自媒体账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if(result.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        if(wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,result.getErrorMessage());
        }
        //如果没有开通 则保存信息开通账户
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setImage(apUser.getImage());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        //调用保存方法  保存信息
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(!saveResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        return saveResult.getData();
    }
    @Autowired
    private ArticleFeign articleFeign;

    /**创建作者信息
     *
     * @param wmUser
     */
    private void createApAuthor(WmUser wmUser) {
        //远程调用ArticleFeign接口 查询用户是否已经创建过作者信息
        ResponseResult<ApAuthor> result = articleFeign.findAllByUserId(wmUser.getId());
        if (result.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        ApAuthor apAuthor = result.getData();
        //判断作者信息是否存在  不等于null说明存在
        if(apAuthor!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,result.getErrorMessage());
        }
        //如果没有开通 则保存信息开通账户
        apAuthor=new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        //远程调用保存方法
        ResponseResult saveResult = articleFeign.save(apAuthor);
        //若保存失败抛出异常
        if(!saveResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
    }
}
